package com.dailyblue.java.cloud.consumer.basic.service.impl;

import com.dailyblue.java.cloud.consumer.basic.service.ConsumerService;
import com.dailyblue.java.commons.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/*
第一种服务的消费者消费服务的提供者方法的方式
 */
@Service
@Slf4j
public class Consumer01ServiceImpl implements ConsumerService {
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;

    @Override
    public JsonResult a() {
        log.info("进入消费者的a方法");
        // 获取到实例名为provider的服务
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        log.info("获取到实例名为provider的所有实例");
        // 模拟的时候只有一个实例
        ServiceInstance instance = list.get(0);
        // 调用这个实例的controller的方法
        String uri = instance.getUri().toString() + "/provider/a";
        log.info("uri路径是：{}", uri);
        // 第一个参数是：访问路径，第二个参数是：返回结果类型
        JsonResult result = restTemplate.getForObject(uri, JsonResult.class);
        return result;
    }

    /*
    模拟了服务提供者多实例情况
    随机方式
     */
    @Override
    public JsonResult b(int a) {
        // 1. 获取到服务的提供者实例
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        int random = (int) (Math.random() * list.size());
        ServiceInstance service = list.get(random);
        // 2. 获取到uri
        String uri = service.getUri().toString() + "/provider/b/" + a;
        // 3. 调用并获取返回结果
        JsonResult result = restTemplate.getForObject(uri, JsonResult.class);
        return result;
    }

    /*
    模拟了服务提供者多实例情况
    轮询方式
     */
    int index = 0;

    @Override
    public JsonResult c(int a, String b) {
        List<ServiceInstance> list = discoveryClient.getInstances("provider");
        ServiceInstance service = list.get(index);
        if (index < list.size()-1) {
            index++;
        }else{
            index = 0;
        }
        String uri = service.getUri().toString() + "provider/c/" + a + "/" + b;
        JsonResult result = restTemplate.getForObject(uri, JsonResult.class);
        return result;
    }
}
